#!/usr/bin/env node

/**
 * 用户API性能测试脚本
 * 用于测试 /api/users/{id} 接口的响应时间
 */

const https = require('https');
const http = require('http');

// 配置
const config = {
  baseUrl: 'http://localhost:3000', // 修改为你的服务器地址
  testUserIds: [1, 2, 3, 4, 5], // 测试的用户ID列表
  iterations: 5, // 每个用户ID测试次数
};

// 发送HTTP请求的Promise封装
function makeRequest(url) {
  return new Promise((resolve, reject) => {
    const startTime = Date.now();
    const protocol = url.startsWith('https') ? https : http;
    
    const req = protocol.get(url, (res) => {
      let data = '';
      
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        const endTime = Date.now();
        const responseTime = endTime - startTime;
        
        try {
          const jsonData = JSON.parse(data);
          resolve({
            success: true,
            responseTime,
            statusCode: res.statusCode,
            data: jsonData
          });
        } catch (error) {
          resolve({
            success: false,
            responseTime,
            statusCode: res.statusCode,
            error: 'JSON解析失败'
          });
        }
      });
    });
    
    req.on('error', (error) => {
      const endTime = Date.now();
      const responseTime = endTime - startTime;
      resolve({
        success: false,
        responseTime,
        error: error.message
      });
    });
    
    req.setTimeout(10000, () => {
      req.destroy();
      resolve({
        success: false,
        responseTime: 10000,
        error: '请求超时'
      });
    });
  });
}

// 测试单个用户ID
async function testUserId(userId) {
  const url = `${config.baseUrl}/api/users/${userId}`;
  const results = [];
  
  console.log(`\n测试用户ID: ${userId}`);
  console.log('='.repeat(50));
  
  for (let i = 0; i < config.iterations; i++) {
    process.stdout.write(`第 ${i + 1} 次测试... `);
    
    const result = await makeRequest(url);
    results.push(result);
    
    if (result.success) {
      console.log(`✅ ${result.responseTime}ms (状态码: ${result.statusCode})`);
    } else {
      console.log(`❌ ${result.responseTime}ms (错误: ${result.error})`);
    }
    
    // 避免请求过于频繁
    await new Promise(resolve => setTimeout(resolve, 100));
  }
  
  return results;
}

// 计算统计信息
function calculateStats(results) {
  const successResults = results.filter(r => r.success);
  const responseTimes = successResults.map(r => r.responseTime);
  
  if (responseTimes.length === 0) {
    return {
      successRate: 0,
      avgResponseTime: 0,
      minResponseTime: 0,
      maxResponseTime: 0,
      totalRequests: results.length
    };
  }
  
  const sum = responseTimes.reduce((a, b) => a + b, 0);
  const avg = sum / responseTimes.length;
  const min = Math.min(...responseTimes);
  const max = Math.max(...responseTimes);
  
  return {
    successRate: (successResults.length / results.length) * 100,
    avgResponseTime: Math.round(avg),
    minResponseTime: min,
    maxResponseTime: max,
    totalRequests: results.length,
    successfulRequests: successResults.length
  };
}

// 主测试函数
async function runPerformanceTest() {
  console.log('🚀 开始用户API性能测试');
  console.log(`📍 测试地址: ${config.baseUrl}`);
  console.log(`👥 测试用户: ${config.testUserIds.join(', ')}`);
  console.log(`🔄 每用户测试次数: ${config.iterations}`);
  
  const allResults = {};
  const overallStats = [];
  
  // 测试每个用户ID
  for (const userId of config.testUserIds) {
    const results = await testUserId(userId);
    allResults[userId] = results;
    
    const stats = calculateStats(results);
    overallStats.push({ userId, ...stats });
    
    console.log(`\n📊 用户 ${userId} 统计:`);
    console.log(`   成功率: ${stats.successRate.toFixed(1)}%`);
    console.log(`   平均响应时间: ${stats.avgResponseTime}ms`);
    console.log(`   最快响应: ${stats.minResponseTime}ms`);
    console.log(`   最慢响应: ${stats.maxResponseTime}ms`);
  }
  
  // 总体统计
  console.log('\n' + '='.repeat(60));
  console.log('📈 总体性能报告');
  console.log('='.repeat(60));
  
  const allResponseTimes = overallStats
    .filter(s => s.successfulRequests > 0)
    .map(s => s.avgResponseTime);
  
  if (allResponseTimes.length > 0) {
    const overallAvg = Math.round(
      allResponseTimes.reduce((a, b) => a + b, 0) / allResponseTimes.length
    );
    const overallMin = Math.min(...overallStats.map(s => s.minResponseTime));
    const overallMax = Math.max(...overallStats.map(s => s.maxResponseTime));
    
    console.log(`🎯 整体平均响应时间: ${overallAvg}ms`);
    console.log(`⚡ 最快响应时间: ${overallMin}ms`);
    console.log(`🐌 最慢响应时间: ${overallMax}ms`);
    
    // 性能评级
    let grade = '';
    if (overallAvg < 100) grade = '🟢 优秀';
    else if (overallAvg < 300) grade = '🟡 良好';
    else if (overallAvg < 1000) grade = '🟠 一般';
    else grade = '🔴 需要优化';
    
    console.log(`📊 性能评级: ${grade}`);
  }
  
  console.log('\n✅ 测试完成!');
  
  // 优化建议
  const slowUsers = overallStats.filter(s => s.avgResponseTime > 500);
  if (slowUsers.length > 0) {
    console.log('\n💡 优化建议:');
    console.log('   1. 检查数据库索引是否已正确创建');
    console.log('   2. 考虑为大数据量用户添加缓存');
    console.log('   3. 监控数据库查询执行计划');
    console.log(`   4. 慢响应用户: ${slowUsers.map(u => u.userId).join(', ')}`);
  }
}

// 运行测试
if (require.main === module) {
  runPerformanceTest().catch(console.error);
}

module.exports = { runPerformanceTest, testUserId, calculateStats };